/*
Copyright (c) 2020-2022, Huawei Technologies Co., Ltd
 All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

* Description: 图表可视化插件数据接收类
*/

#ifndef CHART_DISPLAY_BASE_H
#define CHART_DISPLAY_BASE_H

#include "rviz/message_filter_display.h"


namespace chart_plugin {
template <class MessageType> class ChartDisplayBase : public rviz::_RosTopicDisplay {
public:
    ChartDisplayBase()
    {
        QString messageType = QString::fromStdString(ros::message_traits::datatype<MessageType>());
        topic_property_->setMessageType(messageType);
        topic_property_->setDescription(messageType + " topic to subscribe to.");
#ifdef NOETIC
        queue_size_property_->setHidden(true);
#endif
    }

    virtual ~ChartDisplayBase()
    {
        UnSubscribe();
    }

    /*
     * 功能：插件的初始化函数，在Rviz对插件进行初始化时调用，继承自父类
     * 输入参数：无
     * 输出参数：无
     * 返回值：无
     */
    void onInitialize() override
    {
        sub.registerCallback(boost::bind(&ChartDisplayBase<MessageType>::IncomingMessage, this, _1));
    }

    /*
     * 功能：通知rviz Display清除其状态，继承自父类并重写
     * 输入参数：无
     * 输出参数：无
     * 返回值：无
     */
    void reset() override
    {
        Display::reset();
        messagesReceived = 0;
    }

    /*
     * 功能：设置插件订阅的topic
     * 输入参数：topic-需要订阅的topic，datatype-需要订阅的消息的数据类型
     * 输出参数：无
     * 返回值：无
     */
    void setTopic(const QString &topic, const QString &datatype) override
    {
        topic_property_->setString(topic);
    }

protected:
    /*
     * 功能：取消订阅topic
     * 输入参数：无
     * 输出参数：无
     * 返回值：无
     */
    virtual void UnSubscribe()
    {
        sub.unsubscribe();
    }

    /*
     * 功能：启动订阅topic
     * 输入参数：无
     * 输出参数：无
     * 返回值：无
     */
    virtual void Subscribe()
    {
        if (!isEnabled()) {
            return;
        }

        try {
            ros::TransportHints transportHint = ros::TransportHints().reliable();

            if (unreliable_property_->getBool()) {
                transportHint = ros::TransportHints().unreliable();
            }
            const uint32_t queueSize = 10;
            sub.subscribe(update_nh_, topic_property_->getTopicStd(), queueSize, transportHint);
            setStatus(rviz::StatusProperty::Ok, "Topic", "OK");
            setStatus(rviz::StatusProperty::Warn, "Data receiving failure", "No Display data was received in the last 1 second.");
        } catch (ros::Exception &e) {
            setStatus(rviz::StatusProperty::Error, "Topic", QString("Error subscribing: ") + e.what());
        }
    }

    /*
     * 功能：topic消息处理函数，子类继承者根据自己的数据做覆盖处理
     * 输入参数：msg-topic订阅得到的数据消息
     * 输出参数：无
     * 返回值：无
     */
    virtual void ProcessMessage(const typename MessageType::ConstPtr &msg) = 0;

    /*
     * 功能：topic处理函数，当监听到消息，该处理函数被触发调用
     * 输入参数：msg-topic订阅得到的数据消息
     * 输出参数：无
     * 返回值：无
     */
    void IncomingMessage(const typename MessageType::ConstPtr &msg)
    {
        if (!msg) {
            ProcessMessage(msg);
            return;
        }

        ++messagesReceived;

        setStatus(rviz::StatusProperty::Ok, "Topic", QString::number(messagesReceived) + " messages received");
        deleteStatus("Data receiving failure");
        ProcessMessage(msg);
    }

    /*
     * 功能：重置并重新启动topic订阅
     * 输入参数：无
     * 输出参数：无
     * 返回值：无
     */
    void updateTopic() override
    {
        UnSubscribe();
        reset();
        Subscribe();
    }

    /*
     * 功能：插件使能时需要进行的操作，这里启动topic订阅
     * 输入参数：无
     * 输出参数：无
     * 返回值：无
     */
    void onEnable() override
    {
        Subscribe();
    }

    /*
     * 功能：插件失活时需要进行的操作，继承自rviz::Display
     * 输入参数：无
     * 输出参数：无
     * 返回值：无
     */
    void onDisable() override
    {
        UnSubscribe();
        reset();
    }

#ifdef NOETIC
    /*
     * 在noetic版本的rviz中，父类rviz::_RosTopicDisplay新增了以下两个纯虚函数
     * 由于曲线插件不会用到这两个函数，所以实现为空
     */

    void updateQueueSize() override
    {}

    void processTypeErasedMessage(boost::shared_ptr<const void> type_erased_msg) override
    {}
#endif

    using ChartDisplayClass = ChartDisplayBase<MessageType>;

    message_filters::Subscriber<MessageType> sub {};
    uint32_t messagesReceived { 0 };
};
} // end namespace chart_plugin

#endif // CHART_DISPLAY_BASE_H
